package com.gljx.web.service.impl;

import com.gljx.constant.ActivitiKey;
import com.gljx.util.ActitiviUtil;
import com.gljx.util.GetUserSession;
import com.gljx.util.ServerResponse;
import com.gljx.web.Entity.Message;
import com.gljx.web.Entity.Student;
import com.gljx.web.Entity.SubjectFile;
import com.gljx.web.Entity.SubjectFileEntry;
import com.gljx.web.dao.CommonDao;
import com.gljx.web.dao.StudentMapper;
import com.gljx.web.dao.SubjectFileMapper;
import com.gljx.web.service.MessageService;
import com.gljx.web.service.SubjectFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class SubjectFileServiceImpl extends CommonDao implements SubjectFileService {

	@Autowired
	private SubjectFileMapper subjectFileMapper;

	@Autowired
	private StudentMapper studentMapper;

	@Autowired
	private MessageService messageService;

    //导入activiti工具
    ActitiviUtil activitiUtil = new ActitiviUtil();

	/**
	 * 插入记录
	 */
	@Override
	public void insertSubjectFile(SubjectFile subjectFile) {
		// TODO Auto-generated method stub
		subjectFileMapper.insertSelective(subjectFile);
	}
	
	
	
	
	/**
	 * 批量删除
	 */
	@Override
	public void delSubjectFile(String[] fids) {
		// TODO Auto-generated method stub
		subjectFileMapper.delSubjectFile(fids);
	}


	/**
	 * 根据fid查询
	 */
	@Override
	public SubjectFile selectSubjectFileByFid(String fid) {
		// TODO Auto-generated method stub
		return subjectFileMapper.selectSubjectFileByFid(fid);
	}



	/**
	 * 更新
	 * (non-Javadoc)
	 * @see com.gljx.web.service.SubjectFileService#updateSubjectFile(com.gljx.web.Entity.SubjectFile)
	 */
	@Override
	public void updateSubjectFile(SubjectFile subjectFile) {
		// TODO Auto-generated method stub
		subjectFileMapper.updateByPrimaryKeySelective(subjectFile);
	}




	/**
	 *取分页数据    dmz 20160921
	 *@param pindex 页码
	 *@param psql SQL语句，需要带 rownum rn 例如：select rownum rn,t.* from zzda t
	 *@param psize 每页记录数
	 * */
	@Override
	public Map<String, Object> selectPage(int pindex, String psql, int psize) {
		  Map<String, Object> paramMap = new HashMap<String, Object>();
	       paramMap.put("Pindex", pindex);
	       paramMap.put("Psql", psql);
	       paramMap.put("Psize", psize);
	       paramMap.put("Pcount", oracle.jdbc.OracleTypes.INTEGER);
	       paramMap.put("v_cur", oracle.jdbc.OracleTypes.CURSOR);
	       this.getSqlSession().select("com.gljx.web.dao.SubjectFileMapper.pagemap", paramMap, null);
	       return  paramMap;
	}

	/**
	 * 取记录总数      dmz 20160921
	 * @param psql   SQL语句
	 * @return
	 */
	@Override
	public Map<String, Object> selectPageCount(String psql) {
		   Map<String, Object> paramMap = new HashMap<String, Object>();
	       paramMap.put("Psql", psql);
	       paramMap.put("Pcount", oracle.jdbc.OracleTypes.INTEGER);
	       this.getSqlSession().select("com.gljx.web.dao.SubjectFileMapper.pagecount", paramMap, null);
	       return paramMap;
	}


	@Override
	public String checkSubject(List<SubjectFileEntry> subjectFileEntries, SubjectFile subjectFile, String state, String agreed, String auditcomment, String submitFlag,HttpServletRequest request) {
		if ("5".equalsIgnoreCase(state)) {
			if(auditcomment == null || auditcomment.equals(""))
				auditcomment="同意";
			return checkFlow(subjectFileEntries,subjectFile, agreed, auditcomment,request);
		}
		if ("3".equalsIgnoreCase(state)) {
			uncheckFlow(subjectFile,submitFlag,request);
			subjectFile.setCfbillstate(Long.valueOf("3"));
			subjectFile.setFsourcefunction(auditcomment);
			subjectFileMapper.updateByPrimaryKeySelective(subjectFile);
			return "反审核成功！";
		}
		return null;
	}

	//1.提交
	//用户点击提交按钮时我们将流程创建出来
	public void submitFlow(SubjectFile subjectFile, String submitFlag,HttpServletRequest request) {
		//1.这里是你修改单据的代码，此处你应该有一个单据


		//2.将这个单据编号和你需要保存的流程变量存入map集合中
		Map<String,Object> map = new HashMap<String,Object>();

		map.put(ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_fileAndSkill_gl : ActivitiKey.DrivingSys_fileAndSkill_nc,subjectFile.getFnumber());//使用你自己单据的key，或者用默认的
		/*com.gljx.constant.ActivitiKey 中存入流程相关的常量，最好将流程定义的key也存入其中*/
		//3.调用方法
		if (activitiUtil.notTask.equals(submitFlag)) {
			//3.调用方法
			String piID = activitiUtil.creatFlow(
					ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_fileAndSkill_gl : ActivitiKey.DrivingSys_fileAndSkill_nc,  //指定要启动的流程定义
					map                     //流程变量
			);
			//4.如果你有“提交”这个流程，那么你还要补上一步，将流程推进到提交的下一步
			Message message = activitiUtil.completeFlowByPiID(piID);
			if (message != null) {
				message.setMessage("科目一档案交接-审核 "+subjectFile.getFnumber());//消息内容
				message.setUrl("/selSubjectFileById?fid=" + subjectFile.getFid());//详细路径
				messageService.insert(message);
			}

			///////////////////////////////        二、当前有进行的流程       ///////////////////////////
			/////////////////////////////////////////////////////////////////////////////////////////

			/*详情页获取单据是否有历史记录，放到前台，然后取回 传到提交方法中判断*/
		}else if(activitiUtil.FINISH.equals(submitFlag)){
            //3.调用方法
            String piID = activitiUtil.creatFlow(
                    ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_fileAndSkill_gl : ActivitiKey.DrivingSys_fileAndSkill_nc,  //指定要启动的流程定义
                    map                     //流程变量
            );
            //4.如果你有“提交”这个流程，那么你还要补上一步，将流程推进到提交的下一步
            Message message = activitiUtil.completeFlowByPiID(piID);
            if (message != null) {
                message.setMessage("科目一档案交接-审核 "+subjectFile.getFnumber());//消息内容
                message.setUrl("/selSubjectFileById?fid=" + subjectFile.getFid());//详细路径
                messageService.insert(message);
            }
        }else{
			/*审核过程中的单据被打回调此方法*/
			Message message2 = activitiUtil.complteFlowByVariable(
					ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_fileAndSkill_gl : ActivitiKey.DrivingSys_fileAndSkill_nc,  //指定要启动的流程定义
					subjectFile.getFnumber()                     //流程变量
			);

			if (message2 != null) {
				message2.setMessage("科目一档案交接-提交 "+subjectFile.getFnumber());//消息内容
				message2.setUrl("/selSubjectFileById?fid=" + subjectFile.getFid());//详细路径
				messageService.insert(message2);
			}
		}
	}


	//2.审核
	//用户点击审核按钮时的操作
	public String checkFlow(List<SubjectFileEntry> subjectFileEntries,SubjectFile subjectFile, String agreed, String auditcomment,HttpServletRequest request) {
		//1.获取页面传来的单据ID

		//2.根据单据来推进指定流程

		//2.1审核有两种情况同意与不同意，不同意可能有批注


		//2.2使用这个方法必须保证usertask节点与其子连线key值符合要求
		Object returnMsg =
				activitiUtil
						.auditComplteMessage(
								ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_fileAndSkill_gl : ActivitiKey.DrivingSys_fileAndSkill_nc,
								subjectFile.getFnumber(),                  //单据
								Integer.valueOf(agreed),                 //1、0是否同意取决于你的流程图
								auditcomment              //批注，直接把前端传过来的string塞进来
						);
		if(returnMsg instanceof Message){
			Message resultMsg = (Message) returnMsg;
			resultMsg.setMessage("科目一档案交接-审核 "+subjectFile.getFnumber());//消息内容
			resultMsg.setUrl("/selSubjectFileById?fid=" + subjectFile.getFid());//详细路径
			messageService.insert(resultMsg);
			return "审核成功!";
		} else if(activitiUtil.notAssign .equals(returnMsg)) {
			return  "当前用户不是要求的经办人";
		} else if(activitiUtil.FINISH.equals(returnMsg)) {
			subjectFile.setCfbillstate((long) 5);
			Student student = new Student();
			for(SubjectFileEntry subjectFileEntry:subjectFileEntries){
				student.setCfdajj((long) 1);
				student.setFid(subjectFileEntry.getCfstudentid());
				studentMapper.updateByPrimaryKeySelective(student);
			}
			subjectFileMapper.updateByPrimaryKeySelective(subjectFile);
			return  "此流程成功推进，并且此流程已经结束";
		} else if(activitiUtil.SUCCESS.equals(returnMsg)) {
			return  "此流程成功推进";
		} else  {
			return "没有找到正在进行的相关流程";
		}

	}

	//3.反审核
	//用户点击审核按钮时的操作
	public ServerResponse uncheckFlow(SubjectFile subjectFile , String submitFlag, HttpServletRequest request) {
		//需要注意反审核按钮是位于流程之外只与权限关联的。
		//这里统一跳提交按钮处
		//同样的流程图需要符合规范

		///////////////////////////////         一、当前没有流程       /////////////////////////////
		/////////////////////////////////////////////////////////////////////////////////////////
		if (activitiUtil.notTask.equals(submitFlag)) {
			//直接修改单据状态为“保存”状态
			Message message2 = activitiUtil.getMessage(
					ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_fileAndSkill_gl : ActivitiKey.DrivingSys_fileAndSkill_nc,
					subjectFile.getFnumber()                  //单据
			);

			if (message2 != null) {
				message2.setMessage("科目一档案交接-反审核 "+subjectFile.getFnumber());//消息内容
				message2.setUrl("/selSubjectFileById?fid=" + subjectFile.getFid());//详细路径
				messageService.insert(message2);
			}
			return ServerResponse.createBySuccessMessage("反审核成功！");
			///////////////////////////////        二、当前有进行的流程       ///////////////////////////
			/////////////////////////////////////////////////////////////////////////////////////////
		} else {

			Object result = activitiUtil.jumpActivtiMessage(
					ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_fileAndSkill_gl : ActivitiKey.DrivingSys_fileAndSkill_nc,
					subjectFile.getFnumber(),                  //单据
					"不同意："
			);
			if (result instanceof Message) {
				Message resultMsg = (Message) result;
						resultMsg.setMessage("科目一档案交接-反审核 "+subjectFile.getFnumber());//消息内容
						resultMsg.setUrl("/selSubjectFileById?fid=" + subjectFile.getFid());//详细路径
				messageService.insert(resultMsg);
			} else if (activitiUtil.SUCCESS.equals(result)) {
				System.out.println("成功");

			} else if (activitiUtil.notActiviti.equals(result)) {
				System.out.println("找不到流程节点");

			} else if (activitiUtil.notTask.equals(result)) {
				System.out.println("没有找到任务");
			}
			return ServerResponse.createBySuccessMessage("反审核成功！");
		}
	}
	//3.反审核
	//用户点击审核按钮时的操作
	public void outTimeuncheckFlow(SubjectFile subjectFile) {
		//需要注意反审核按钮是位于流程之外只与权限关联的。
		//这里统一跳提交按钮处
		//同样的流程图需要符合规范

		//1.获取页面传来的单据ID
		/*String danju = "YHTDF202165416531321";*/

		String result = activitiUtil.jumpActivti(
				ActivitiKey.FNUMBER,
				subjectFile.getFnumber()                 //单据
		);
		if(activitiUtil.SUCCESS.equals(result)) {
			System.out.println("成功");
		}else if(activitiUtil.notActiviti.equals(result)) {
			System.out.println("找不到流程节点");
		}else if(activitiUtil.notTask.equals(result)) {
			System.out.println("没有找到任务");
		}
	}

    /**
     * @Author lcx
     * @Date 2018/2/7 0007 下午 2:05
     * 查询经办人是否匹配
     */
    public String selectAuditPersonByAdd(Object fnumber, String result) {
        if (activitiUtil.notTask.equals(result)) {
            System.out.println("改单据没有对应流程");
            return activitiUtil.notTask;
        } else if (activitiUtil.FINISH.equals(result)) {
            System.out.println("流程已结束");
            return activitiUtil.FINISH;
        }//剩下两种是该任务进行中
        else if (activitiUtil.notAssign.equals(result)) {
            System.out.println("经办人不匹配");
            return activitiUtil.notAssign;
        } else if (activitiUtil.ISPOWER.equals(result)) {
            System.out.println("当前用户可以审核该单据");
            return activitiUtil.ISPOWER;
        } else {
            return "";
        }
    }
	
	
}
